package service;

import ThreadService.BackupThread;
import com.gexin.fastjson.JSONObject;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

public class PureLogDb {

    public static final List<String> memoryList = new ArrayList<>();
    private static IOService ioService;
    private static final String KEY = "key";
    private static final String TYPE = "type";

    public PureLogDb() {
        //初始化io
        ioService = new IOService();
        //初始化对内存内数据进行检测
        if (memoryList.size() <= 0) {
            //如果内存不存在数据就进行读取备份文件中的数据，如果备份文件中存在数据就将其同步至内存中
            List<String> backup = ioService.read();
            if (null != backup && backup.size() > 0) memoryList.addAll(backup);
        }
    }


    /**
     * set
     *
     * @param key
     * @param value
     */
    public void putVal(String key, String value) {
        //往内存中写值
        SetCommand setCommand = new SetCommand(key, value);
        memoryList.add(setCommand.toString());
        //往备份文件中写值
        Thread thread2 = new BackupThread(key, value, CommandTypeEnum.Set);
        thread2.start();
    }

    /**
     * 删除
     */
    public void rmVal(String key) {
        RmCommand rmCommand = new RmCommand(key);
        memoryList.add(rmCommand.toString());
        ioService.write(rmCommand.toString());
        //往备份文件中写值
        Thread thread2 = new BackupThread(key,null, CommandTypeEnum.Rm);
        thread2.start();
    }

    /**
     * get获取
     *
     * @param key
     * @return
     */
    public String getVal(String key) {
        LinkedList<Command> values = new LinkedList<>();
        for (int i = 0; i < memoryList.size(); i++) {
            JSONObject kv = JSONObject.parseObject(memoryList.get(i));
            String key1 = kv.getString(KEY);
            if (null != key1 && key.equals(key1)) {
                if (kv.getString(TYPE).equals(CommandTypeEnum.Set.name())) values.add(kv.toJavaObject(SetCommand.class));
                if (kv.getString(TYPE).equals(CommandTypeEnum.Rm.name())) values.add(kv.toJavaObject(RmCommand.class));
            }
        }
        if (values.size() > 0) return values.getLast().toString();
        return null;
    }
}
